package com.videoaggre.zcl.parse

import android.content.Context
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.OnLifecycleEvent
import com.kingja.loadsir.callback.SuccessCallback
import com.kingja.loadsir.core.LoadService
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.videoaggre.zcl.common.*
import com.videoaggre.zcl.helper.loadsir.LoadingCallback
import com.videoaggre.zcl.ui.dialog.LoadingDialog
import com.videoaggre.zcl.ui.dialog.safeDismissDialog
import com.videoaggre.zcl.utils.Logger

typealias SuccessParse = (html: String) -> Unit

open class BaseParse(
    context: Context? = null,
    lifecycleOwner: LifecycleOwner,
    private val url: String,
    private var loadService: LoadService<*>? = null,
    private var refreshLayout: RefreshLayout? = null,
    private val loadOrDialog: Boolean = false,
    private val successParse: SuccessParse? = null,
) : IParse, LifecycleObserver {
    private var mLoadingDialog: LoadingDialog? = null

    init {
        lifecycleOwner.lifecycle.addObserver(this)
        if ((loadService == null || loadOrDialog) && context != null)
            mLoadingDialog = LoadingDialog(context)
    }

    private var mCancel: CancelCallback? = null
    override fun injectCancel(cancel: CancelCallback) {
        mCancel = cancel
    }

    override fun url() = url

    override fun cancel() {
        mCancel?.invoke()
        mLoadingDialog?.safeDismissDialog()
        loadService = null
        refreshLayout?.stopRefresh()
    }

    override fun start() {
        if (loadService != null && loadService!!.currentCallback != SuccessCallback::class.java) {
            loadService?.showLoadingBeforeSuccessCallback()
        } else {
            mLoadingDialog?.show()
        }
    }

    override fun success(html: String) {
        loadService?.showSuccess()
        successParse?.invoke(html)
        mCancel = null
        mLoadingDialog?.safeDismissDialog()
        refreshLayout?.stopRefresh()
    }

    override fun error() {
        loadService?.showErrorCallback()
        mLoadingDialog?.safeDismissDialog()
        refreshLayout?.stopRefresh()
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    private fun onDestroy() {
        cancel()
        mCancel = null
        mLoadingDialog?.safeDismissDialog()
        mLoadingDialog = null
        loadService = null
        refreshLayout?.stopRefresh()
    }
}